/**
 * AI Error Helper Component
 * Adds AI help buttons to error logs in the debug panel
 */

/**
 * Setup AI help buttons for error logs in the debug panel
 * @param {Function} customChatRunner - The function to handle AI error explanation
 */
export function setupErrorAIHelper(customChatRunner) {
  let observer = null;

  /**
   * Process error logs and add AI help buttons
   */
  function processErrorLogs() {
    // Find all error logs with the class debugPanel_logError__7Xp2t
    // If that specific class is not found, try to find error messages more generically
    let errorLogs = document.querySelectorAll(".debugPanel_logError__7Xp2t");

    // If no logs found with the specific class, look for more generic error logs
    if (errorLogs.length === 0) {
      const debugConsole = document.querySelector(
        ".script-editor_debugPanel__b3m_6"
      );
      if (debugConsole) {
        // Find elements that might contain error messages (typically red text or containing "error" text)
        const possibleErrorLogs = Array.from(
          debugConsole.querySelectorAll("div, span, p")
        ).filter((el) => {
          const style = window.getComputedStyle(el);
          const text = el.textContent.toLowerCase();

          // Look for red text or error-related content
          return (
            (style.color.includes("255") &&
              style.color.includes("0") &&
              style.color.includes("0")) || // Red color
            text.includes("error") ||
            text.includes("exception") ||
            text.includes("failed")
          );
        });

        // Add our custom class to these elements for styling
        possibleErrorLogs.forEach((el) => {
          el.classList.add("debugPanel_logError__7Xp2t");
        });

        // Update our errorLogs collection
        errorLogs = document.querySelectorAll(".debugPanel_logError__7Xp2t");
      }
    }

    // Process each error log
    errorLogs.forEach((errorLog) => {
      // Only add button if it doesn't already have one
      if (!errorLog.querySelector(".ai-explain-error-btn")) {
        // Create the AI help button
        const aiHelpBtn = document.createElement("div");
        aiHelpBtn.className = "ai-explain-error-btn";
        aiHelpBtn.title = "AI解释此错误";

        // Get the error text
        const errorText = errorLog.textContent || "";

        // Set up click handler
        aiHelpBtn.addEventListener("click", (e) => {
          e.stopPropagation(); // Prevent triggering parent click events

          // Add loading state
          aiHelpBtn.classList.add("loading");

          try {
            // Call the AI to explain the error
            const result = customChatRunner(
              "explain_error",
              `请解释这个错误，并提供修复建议：${errorText}`
            );

            // 检查结果是否是Promise
            if (result && typeof result.then === "function") {
              // 如果是Promise，使用finally
              result
                .then(() => {
                  // Remove loading state when done
                  aiHelpBtn.classList.remove("loading");
                })
                .catch(() => {
                  // 确保在出错时也移除loading状态
                  aiHelpBtn.classList.remove("loading");
                });
            } else {
              // 如果不是Promise，立即移除loading状态
              setTimeout(() => {
                aiHelpBtn.classList.remove("loading");
              }, 1000); // 给一点延迟以提供更好的视觉反馈
            }
          } catch (error) {
            console.error("AI解释错误时出现异常:", error);
            aiHelpBtn.classList.remove("loading");
          }
        });

        // Add the button to the error log
        errorLog.appendChild(aiHelpBtn);

        // 确保错误日志样式已正确设置
        errorLog.style.position = "relative";

        // 确保错误信息不会被按钮遮挡
        const textNodes = Array.from(errorLog.childNodes).filter(
          (node) =>
            node.nodeType === 3 || (node.nodeType === 1 && node !== aiHelpBtn)
        );

        if (textNodes.length > 0) {
          // 确保文本内容有足够的右侧边距
          textNodes.forEach((node) => {
            if (node.nodeType === 1) {
              // 元素节点
              node.style.paddingRight = "45px";
              node.style.display = "inline-block";
              node.style.maxWidth = "calc(100% - 45px)";
            }
          });
        }
      }
    });
  }

  /**
   * Initialize the observer to watch for new error logs
   */
  function initObserver() {
    // Disconnect existing observer if any
    if (observer) {
      observer.disconnect();
    }

    // Find the debug panel
    const debugPanel = document.querySelector(
      ".script-editor_debugPanel__b3m_6"
    );
    if (!debugPanel) return;

    // Create a mutation observer to watch for changes in the debug panel
    observer = new MutationObserver((mutations) => {
      processErrorLogs();
    });

    // Start observing the debug panel for DOM changes
    observer.observe(debugPanel, {
      childList: true,
      subtree: true,
      attributes: false,
    });

    // Process existing error logs
    processErrorLogs();

    // Also set up a periodic check for new error logs
    const periodicCheck = setInterval(() => {
      if (document.contains(debugPanel)) {
        processErrorLogs();
      } else {
        clearInterval(periodicCheck);
      }
    }, 2000);
  }

  // Poll for the debug panel, as it might not exist when the script first loads
  const checkDebugPanel = setInterval(() => {
    const debugPanel = document.querySelector(
      ".script-editor_debugPanel__b3m_6"
    );
    if (debugPanel) {
      clearInterval(checkDebugPanel);
      initObserver();
    }
  }, 1000);

  // Return a function to cleanup
  return () => {
    clearInterval(checkDebugPanel);
    if (observer) {
      observer.disconnect();
    }
  };
}
